# coding = utf-8
import sys
from bs4 import BeautifulSoup  # 网页解析，获取数据
import re  # 正则表达式,进行文字匹配
import urllib.request  # 指定URL，获取网页数据
import xlwt  # 进行excel操作


def main():
    baseurl = 'https://tieba.baidu.com/p/7484191815?pn='
    datalist = getData(baseurl)
    askURL(baseurl)
    getData(baseurl)
    saveData(datalist)



findSpeak = re.compile(r'style="display:;">            (.*)<')
delimg = re.compile(r'<img (.*)width="30"/>')


# 获取数据
def getData(baseurl):
    datalist = []
    for i in range(3):
        text = askURL(baseurl + str(i + 1))
        soup = BeautifulSoup(text, 'html.parser')
        for item in soup.find_all('div', class_="d_post_content j_d_post_content"):
            item = str(item)

            # 在data中加入国家
            speak = re.findall(findSpeak, item)
            speak = re.sub(delimg, '', str(speak).replace('<br/>', ' '))  # 只保留评论内容，删除图片路径及换行

            if len(speak) >= 3:     # 删除[],尝试过多种方法，最后只能出此下策
                datalist.append(speak)

    return datalist


# 存储数据
def saveData(datalist):
    workBook = xlwt.Workbook(encoding='utf-8')
    worksheet = workBook.add_sheet('评论', cell_overwrite_ok=True)
    for i in range(len(datalist)):
        worksheet.write(i, 0, datalist[i])
    workBook.save('评论.xls')


# 得到指定url网页的数据
def askURL(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.113 Safari/537.36'
    }  # 用户代理，表示告诉服务器我们是什么类型的机器

    req = urllib.request.Request(url, headers=headers)
    html = ''
    try:
        response = urllib.request.urlopen(req, timeout=5)
        html = response.read().decode('utf-8')
    except urllib.error.URLError as e:
        if hasattr(e, 'code'):
            print(e.code)
        if hasattr(e, 'reason'):
            print(e.reason)

    return html


if __name__ == '__main__':
    main()
